package com.cloud.job.snail;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.cloud.api.domain.job.Addr;
import com.cloud.api.domain.job.ServiceStation;
import com.cloud.api.domain.stats.Maintenance;
import com.cloud.api.domain.stats.VehicleDataRepair;
import com.cloud.job.service.IMaintenanceService;
import com.cloud.job.service.IServiceStationService;
import com.cloud.job.service.IVehicleDataService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class VehicleStop {

    @Resource
    private RequestBaidu requestBaidu;
    @Resource
    private IVehicleDataService vehicleDataService;
    @Resource
    private IMaintenanceService maintenanceService;
    @Resource
    private IServiceStationService serviceStationService;
    @Value("${baidu.dis:0.02}")
    private double dis;
    @Value("${baidu.count:10}")
    private int count;


    @JobExecutor(name = "vehicle_stop")
    public void getVehicleStop() throws Exception {
        List<ServiceStation> list = serviceStationService.list();
        List<Maintenance> maintenanceList = new ArrayList<>();
        for (ServiceStation serviceStation : list) {
            if (StrUtil.isBlank(serviceStation.getLat()) || StrUtil.isBlank(serviceStation.getLng())){
                continue;
            }
            //经纬度范围
            BigDecimal latitude = new BigDecimal(serviceStation.getLat());
            double lat = latitude.doubleValue();
            BigDecimal longitude = new BigDecimal(serviceStation.getLng());
            double lng = longitude.doubleValue();
            //先计算查询点的经纬度范围
            double r = 6378.137;//地球半径千米
//            double dis = 0.02;//千米距离
            double dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(lat * Math.PI / 180));
            dlng = dlng * 180 / Math.PI;//角度转为弧度
            double dlat = dis / r;
            dlat = dlat * 180 / Math.PI;
            double minLat = (lat - dlat) * 1000000;
            double maxLat = (lat + dlat) * 1000000;
            double minLng = (lng - dlng) * 1000000;
            double maxLng = (lng + dlng) * 1000000;
            //筛选经纬度范围数据，根据最大时间和最小时间计算时长，并保存数据，vin, 服务站   时间经纬度，时间经纬度，
//            Addr addr = requestBaidu.getAddr(latitude.toString(), longitude.toString());
            List<VehicleDataRepair> vehicleData = vehicleDataService.selectData(minLat, minLng, maxLat, maxLng);
            if (vehicleData != null && !vehicleData.isEmpty()) {
                Map<String, List<VehicleDataRepair>> collect = vehicleData.stream().collect(Collectors.groupingBy(VehicleDataRepair::getVin));
                for (String key : collect.keySet()) {
                    List<VehicleDataRepair> vehicleDataList = collect.get(key);
                    /*ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.registerModule(new JavaTimeModule());
                    // 配置日期格式
                    objectMapper.findAndRegisterModules()
                            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                    String jsonStr = objectMapper.writeValueAsString(vehicleDataList);*/
                    VehicleDataRepair first = vehicleDataList.getFirst();
                    VehicleDataRepair last = vehicleDataList.getLast();
                    Duration between = Duration.between(first.getOpTime(), last.getOpTime());
                    //保留两位小数
                    double totalHours = between.toMillis() / (double) (1000 * 60 * 60);
                    DecimalFormat df = new DecimalFormat("#.##");
                    String formattedTotalHours = df.format(totalHours);

                    /*if (totalHours < 5) {
                        continue;
                    }*/
                    if (vehicleDataList.size() < count) {
                        continue;
                    }

                    Maintenance maintenance = new Maintenance();
                    maintenance.setVin(key);
                    maintenance.setDt(LocalDate.from(first.getOpTime()));
                    maintenance.setStationId(serviceStation.getId());
                    maintenance.setRepairTime(formattedTotalHours);
//                    maintenance.setData(jsonStr);
                    maintenance.setLat(first.getLat());
                    maintenance.setLng(first.getLng());
                    maintenance.setStartTime(first.getOpTime());
                    maintenance.setEndTime(last.getOpTime());
                    maintenance.setMinLat(Double.toString(lat - dlat));
                    maintenance.setMaxLat(Double.toString(lat + dlat));
                    maintenance.setMinLng(Double.toString(lng - dlng));
                    maintenance.setMaxLng(Double.toString(lng + dlng));
                    maintenanceList.add(maintenance);
                }
            }
        }
        maintenanceService.saveBatch(maintenanceList);

    }
}
